import { ref } from "vue";
import { defineStore } from "pinia";
import { useRouter } from "vue-router";
import { generateRoutes } from "@/router/utils";
import { useLayoutStore } from "./layout";
import router from "@/router/index";

import { userLogin, getPermission, byTokenGetUserInfo } from "@/api/user";

export const userStore = defineStore("user", () => {
	// 是否已经登录
	const isLogin = ref(false);
	// 用户信息
	const userInfo = ref({});
	// 用户权限列表
	const roleArr = ref([]);
	// 权限列表
	const permissionArr = ref([]);
	// 路由列表
	const routeArr = ref([]);

	// 用户登录
	const login = async (data) => {
		// 获取用户信息及Token
		try {
			const userInfoRes = await userLogin(data);
			userInfo.value = userInfoRes.data;

			// 将Token保存到本地
			localStorage.setItem("token", userInfoRes.data.token);
		} catch (e) {
			return;
		}

		// 通过Token获取用户权限信息
		try {
			await getUserPermissions();
		} catch (e) {}
	};
	// 根据Token获取用户信息
	const getUserInfo = async () => {
		try {
			const userInfoRes = await byTokenGetUserInfo();
			userInfo.value = userInfoRes.data;
			isLogin.value = true;
		} catch (e) {
			localStorage.removeItem("token");
			// 跳转登录页
			useRouter().push("/login");
			return Promise.reject(e);
		}
	};
	// 根据Token获取权限信息
	const getUserPermissions = async () => {
		try {
			const getPermissionRes = await getPermission();
			roleArr.value = (getPermissionRes.data.role || []).map((item) => item.key);
			permissionArr.value = getPermissionRes.data.allPersmissions;
			routeArr.value = getPermissionRes.data.routePermissions;
			isLogin.value = true;

			generateRoutes(routeArr.value);
		} catch (e) {
			localStorage.removeItem("token");
			// 跳转登录页
			useRouter().push("/login");
			return Promise.reject(e);
		}
	};

	// 用户退出
	const logout = () => {
		isLogin.value = false;
		userInfo.value = {};
		roleArr.value = [];
		permissionArr.value = [];
		// 卸载路由
		routeArr.value.forEach((routeItem) => router.removeRoute(routeItem.name));
		routeArr.value = [];
		router.push("/login");
		useLayoutStore().clearTags();

		localStorage.removeItem("token");
	};

	return { isLogin, userInfo, roleArr, routeArr, permissionArr, login, getUserInfo, getUserPermissions, logout };
});
